<template>
  <div>
    <el-tabs v-if="null != iptables">
      <el-tab-pane label="首页">
        <el-row>
          <el-col :span="24" style="padding: 10px;">
            <card-filter-input-summary :iptables="iptables" v-on:update="actionIptablesRefresh"></card-filter-input-summary>
          </el-col>
          <el-col :span="12" style="padding: 10px;">
            <cart-quick-add v-on:quick-add-success="actionIptablesRefresh"></cart-quick-add>
          </el-col>
          <el-col :span="12" style="padding: 10px;">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>快捷方式</span>
              </div>
              <el-button @click="actionQuickAct('flush')">清空规则</el-button>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane  v-for="(table,tableKey) in iptables" :label="tableKey" :name="tableKey" :key="tableKey">
        <el-collapse value="chain">
          <el-collapse-item v-for="(chain, chainKey) in table" name="chain" :key="chainKey">
            <template slot="title">
              <p style="font-size: 16px;font-weight:600;">{{chainKey}} : [{{chain.default.policy}}]</p>
            </template>
            <el-form :inline="true" v-if="'filter' == tableKey">
              <el-form-item label="默认策略">
                <el-select v-model="iptables[tableKey][chainKey].default.policy" placeholder="未知" size="mini">
                  <el-option :key="'ACCEPT'" :label="'ACCEPT'" :value="'ACCEPT'"></el-option>
                  <el-option :key="'DROP'" :label="'DROP'" :value="'DROP'"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button size="mini" @click="actionChainDefaultPolicyUpdate(tableKey, chainKey)">应用</el-button>
              </el-form-item>
            </el-form>
            <el-table :data="chain.chain" style="width: 100%">
              <el-table-column prop="target" label="调用"></el-table-column>
              <el-table-column prop="protocol" label="协议"></el-table-column>
              <el-table-column prop="source" label="源地址"></el-table-column>
              <el-table-column prop="destination" label="目标地址"></el-table-column>
              <el-table-column prop="comment" label=""></el-table-column>
              <el-table-column align="right">
                <template slot="header">
                  <el-button size="mini" @click="actionChainAddRule(tableKey, chainKey)">添加</el-button>
                </template>
                <template slot-scope="scope">
                  <el-button size="mini" type="danger" @click="actionChainRuleDelete(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
        </el-collapse>
      </el-tab-pane>
    </el-tabs>
    <dialog-rule-edit ref="ruleEditor"/>
  </div>
</template>
<script>
import CartQuickAdd from './CardQuickAdd.vue'
import CardFilterInputSummary from './CardFilterInputSummary.vue'
import IptablesSaveParser from './IptablesSaveParser.js'
import DialogRuleEdit from './DialogRuleEdit.vue'
export default {
    components : {
        'card-filter-input-summary' : CardFilterInputSummary,
        'cart-quick-add' : CartQuickAdd,
        'dialog-rule-edit' : DialogRuleEdit,
    },
    data() {
        return {
            iptables : null,
            client : null,
        }
    },
    /** 页面挂载完成 */
    async mounted () {
        let server = this.$store.getters.serverCurrent;
        this.client = await server.getSshClient();
        await this.iptablesRefresh();
    },
    methods : {
        /** 刷新 IPTABLE */
        async actionIptablesRefresh() {
            await this.iptablesRefresh();
        },

        /** 刷新表 */
        async iptablesRefresh() {
            let iptablesData = await this.client.exec('sudo iptables-save');
            let parser = new IptablesSaveParser(iptablesData);
            this.iptables = await parser.parse();
        },

        /** 增加规则 */
        async actionChainAddRule(tableKey, chainKey) {
            this.$refs.ruleEditor.table = tableKey;
            this.$refs.ruleEditor.chain = chainKey;
            this.$refs.ruleEditor.client = this.client;
            this.$refs.ruleEditor.iptables = this.iptables;
            await this.$refs.ruleEditor.open();
            await this.iptablesRefresh();
            this.$message({type: 'success',message: '操作成功'});
        },

        /** 更新默认策略 */
        async actionChainDefaultPolicyUpdate( tableKey, chainKey ) {
            let policy = this.iptables[tableKey][chainKey].default.policy;
            try {
                await this.$confirm(`此操作将修改 ${tableKey}.${chainKey} 的默认规则为 ${policy}, 是否继续?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });
            } catch {
                return;
            }

            let cmd = `sudo iptables -t ${tableKey} -P ${chainKey} ${policy}`;
            await this.client.exec(cmd);
            this.$message({message: '操作成功',type: 'success'});
        },

        /** 删除策略 */
        async actionChainRuleDelete( rule ) {
            try {
                await this.$confirm(`此操作将删除该规则, 是否继续?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });
            } catch {
                return;
            }

            let cmd = `iptables -t ${rule.table} -D ${rule.chain} ${rule.index}`;
            await this.client.exec(cmd);
            await this.iptablesRefresh();
            this.$message({message: '操作成功',type: 'success'});
        },

        /**  */
        async actionQuickAct( name ) {
            switch ( name ) {
            case 'flush' : 
                await this.handleQuickActionFlush();
                break;
            }
        },

        // 清空规则
        async handleQuickActionFlush( ) {
            try {
                await this.$confirm('此操作将清空规则, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });
            } catch {
                return;
            }
            
            let server = this.$store.getters.serverCurrent;
            await server.exec('iptables -F');
            await this.iptablesRefresh();
            this.$message({message: '操作成功',type: 'success'});
        },
    }
}
</script>